package cn.sea;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by DragonSea
 * on 2018-11-08
 */
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //得到要下载的文件名
       String filename= request.getParameter("filename");
      filename= new String(filename.getBytes("iso8859-1"),"UTF-8");
      //找出这个文件
      String path= this.getServletContext().getRealPath("/upload")+File.separator+getPath(filename);
      File file=new File(path+File.separator+filename);
      if(!file.exists()){
          request.setAttribute("message","你下载的文件不存在！");
          request.getRequestDispatcher("/message.jsp").forward(request,response);
          return;
      }
      //得到原始文件名
        String oldname=file.getName().substring(file.getName().indexOf("_")+1);
      //通知浏览器以下载方式打开下面的数据
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(oldname,"UTF-8"));
       FileInputStream in=new FileInputStream(file);
      int len=0;
      byte[]buffer=new byte[1024];
     OutputStream out = response.getOutputStream();
      while((len=in.read(buffer))>0){
             out.write(buffer,0,len);
      }
      in.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request,response);

    }
    public String getPath(String filename){
        int hashcode=filename.hashCode();
        int dir1=hashcode&0xf;
        int dir2=(hashcode>>4)&0xf;
        return dir1+ File.separator+dir2;
    }
}
